﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Hosting;
using System.Web.Mvc;
using OLAP.Common;
using OLAP.Models;
using OLAP.Models.Partials;

namespace OLAP.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public JsonResult GetPressreleases(string sourceCode, int langId, int sourceId, string searchPhrase, DateTime? fromDate, DateTime? toDate, int pageIndex, int pageJummp)
        {
            int pageItemFrom;
            int pageItemTo;

            pageItemFrom = pageIndex * pageJummp;
            pageItemTo = pageItemFrom + pageJummp;
            pageItemFrom += 1;
            if (string.IsNullOrEmpty(searchPhrase))
                searchPhrase = string.Empty;
            if (!fromDate.HasValue)
                fromDate = DateTime.Now.AddYears(-1);
            if (!toDate.HasValue)
                toDate = DateTime.Now;

            PressreleasesRepository pr = new PressreleasesRepository();
            int totalRow;
            List<Attachment> attachments = new List<Attachment>();
            List<Pressreleases> press = pr.GetAllPressreleases(sourceCode, langId, sourceId, searchPhrase, fromDate, toDate, pageItemFrom, pageItemTo, out totalRow, out attachments);

            List<AttachmentClientSide> attClient = new List<AttachmentClientSide>();
            foreach (var item in attachments)
            {
                attClient.Add(new AttachmentClientSide() { FileName = item.FileName, Id = item.Id, Location = item.Location, MimeType = item.MimeType, PressreleaseId = item.PressreleaseId });
            }
            //Remove Media Binary before return to client side                      
            return Json(new { Data = press, TotalRow = totalRow, DataAttachment = attClient }, JsonRequestBehavior.AllowGet);
        }

        public ActionResult Message(long id)
        {
            PressreleasesRepository pr = new PressreleasesRepository();
            News news = new News();
            news = pr.GetPressreleaseById(id);
            return View(news);
        }

        public ActionResult Video(long id)
        {
            PressreleasesRepository pr = new PressreleasesRepository();
            Attachment atVideo = pr.GetAttactmentById(id);

            return File(atVideo.MediaBinary, atVideo.MimeType, atVideo.FileName);
        }

        public ActionResult News(long id)
        {
            PressreleasesRepository pr = new PressreleasesRepository();
            News news = new News();
            news = pr.GetPressreleaseById(id);
            return View(news);
        }
    }
}
